package com.wdz.mvr.security;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.sql.DataSource;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
                .usersByUsernameQuery("SELECT username,password,enabled " + "FROM users WHERE username = ?")
                .authoritiesByUsernameQuery("SELECT username, role " + "FROM users WHERE username = ?")
                .passwordEncoder(bCryptPasswordEncoder);
    }


    @Override
    public void configure( HttpSecurity http) throws Exception {
        http.authorizeRequests()

//                .antMatchers("/comments/new").hasRole("ADMIN")
//                .antMatchers("/comments/save").hasRole("ADMIN")
//                .antMatchers("/students/new").hasRole("ADMIN")
//                .antMatchers("/students/save").hasRole("ADMIN")
                .antMatchers("/","/**").permitAll()
                .and()
                .formLogin();
//        .formLogin().loginPage("/login-page");
//        可在控制层自定义路径处理登陆请求
    }
}
